﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.APP.Application.Command.Breeding;
using Traceability.APP.DTOS;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrerture.Interfaces;

namespace Traceability.APP.Application.CommandHandle.Breeding
{
    /// <summary>
    /// 养殖信息的详情信息
    /// </summary>
    public class UpdateBreedingCommandHandle:IRequestHandler<UpdateBreedingCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Breeding_Information> BreedDal;
        private readonly IMapper mapper;

        public UpdateBreedingCommandHandle(IBaseRepository<Breeding_Information> breedDal, IMapper mapper)
        {
            BreedDal = breedDal;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(UpdateBreedingCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var user = BreedDal.GetValue(request.ID).Result;

            var model = mapper.Map(request, user);
            model.UpdateTime = DateTime.Now;
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = BreedDal.Update(model).Result;
                tran.Complete();
            }

            if (r > 0)
            {
                result.Code = StateCode.Ok;
                result.Message = "修改成功";
                return Task.FromResult(result);
            }
            else
            {
                result.Code = StateCode.Faile;
                result.Message = "修改失败";
                return Task.FromResult(result);
            }
        }



    }
}
